package com.atguigu.demo.day17springboot.service;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

public class AgeService {
    public static final String DATA_TIME_FORMAT = "yyy-MM-dd HH:mm:ss";
    private final String birthday;
    public AgeService(String birthday){
        this.birthday = birthday;
    }
    public int computerAgeByBirthday(){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATA_TIME_FORMAT);
        LocalDate parse = LocalDate.parse(birthday, dateTimeFormatter);
        LocalDate now = LocalDate.now();
        //检查生日是否在目前日期之后
        if (parse.isAfter(now)){
            return -1;
        }
        //计算年龄
        Period between = Period.between(parse, now);
        return between.getYears();
    }
}
